<?php

class Application_Model_TypeVoitureDAO
{
	protected $_dbTable;

	public function setDbTable($dbTable)
	{
		if(is_string($dbTable))
		{
			$dbTable = new $dbTable();
		}
		if(!$dbTable instanceof Zend_Db_Table_Abstract)
		{
			throw new Exception('Invalid table data gateway provided');
		}
		$this->_dbTable = $dbTable;
		return $this;
	}
 
	public function getDbTable()
	{
		if(null === $this->_dbTable)
		{
			$this->setDbTable('Application_Model_DbTable_TypeVoiture');
		}
		return $this->_dbTable;
	}
	
	public function save(Default_Model_TypeVoiture $typeVoiture)
	{
		$data = array(
			'TYPNUM' => $typeVoiture->getTypNum(),
			'TYPELIBELLE' => $typeVoiture->getTypeLibelle()
		);
 
		if (null === ($voiNum = $typeVoiture->getTypNum()))
		{
			unset($data['TYPNUM']);
			$this->getDbTable()->insert($data);
        }
        else
        {
			$this->getDbTable()->update($data, array('TYPNUM = ?' => $typeVoiture));
		}
	}
	
	public function find($typNum)
	{
		$typeVoiture = new Application_Model_TypeVoiture();

		$result = $this->getDbTable()->find($typNum);
		if(0 == count($result))
		{
			return null;
		}
		$row = $result->current();
		$typeVoiture->setTypNum($row->TYPNUM)
					->setTypeLibelle($row->TYPELIBELLE);
		
		return $typeVoiture;
	}
	
	public function findAll()
	{
		$resultSet = $this->getDbTable()->fetchAll($this->getDbTable()->select()->from('type_voiture',array('TYPNUM'))->order('TYPELIBELLE ASC'));
		$entries = array();
		foreach($resultSet as $row)
		{
			$entries[] = $this->find((int)$row->TYPNUM);
		}
		return $entries;
	}
}